package net.esj.basic.plugins.spring.factory.xml.parser;

import net.esj.basic.dao.hibernate.Hibernate4SessionLocale;
import net.esj.basic.dao.hibernate.HibernateSessionLocale;
import net.esj.basic.dao.hibernate.HibernateSourceLocale;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;

@Deprecated
public class HibernateSourceLocaleBeanDefinitionParser extends
		AbstractSingleBeanDefinitionParser {

	public static final String DEFAULT_HIBERNATE_SESSION_LOCAL = Hibernate4SessionLocale.class.getName();
	
	public static final String DEFAULT_BEAN_NAME = HibernateSourceLocale.class.getName();
	
	
	
	
	@Override
	protected void doParse(Element element, ParserContext parserContext,
			BeanDefinitionBuilder builder) {
		String className = element.getAttribute("class");
		if(!StringUtils.hasText(className)){
			className = DEFAULT_HIBERNATE_SESSION_LOCAL;
		}
		String sessionFactory = element.getAttribute("sessionFactory");//創建hibernateSessionLocale
		if (!StringUtils.hasText(sessionFactory)) {
			sessionFactory = "sessionFactory";
		}
		BeanDefinitionBuilder sessionbuilder = BeanDefinitionBuilder.genericBeanDefinition(
				DEFAULT_HIBERNATE_SESSION_LOCAL);
		sessionbuilder.addPropertyReference("sessionFactory", sessionFactory);
		//String generatedName = parserContext.getReaderContext().generateBeanName(sessionbuilder.getRawBeanDefinition());
		parserContext.registerBeanComponent(
				new BeanComponentDefinition(sessionbuilder.getBeanDefinition(),DEFAULT_HIBERNATE_SESSION_LOCAL));
		
		if (!parserContext.getRegistry().containsBeanDefinition(DEFAULT_BEAN_NAME)) {//創建sourcelocale
			builder.addPropertyReference("source", DEFAULT_HIBERNATE_SESSION_LOCAL);
			parserContext.registerBeanComponent(
					new BeanComponentDefinition(builder.getBeanDefinition(),DEFAULT_BEAN_NAME));
		}
	}

	@Override
	protected String getBeanClassName(Element element) {
		String className = element.getAttribute("class");
		if(!StringUtils.hasText(className)){
			className = DEFAULT_BEAN_NAME;
		}
		return className;
	}

	@Override
	protected String resolveId(Element element,
			AbstractBeanDefinition definition, ParserContext parserContext)
			throws BeanDefinitionStoreException {
		String id = super.resolveId(element, definition, parserContext);
		if(StringUtils.hasText(id)){
			return id;
		}
		return DEFAULT_BEAN_NAME;
	}
	
	
}
